package net.jueb.protoServer.handler.dispatcher;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentHashMap;

import com.google.protobuf.MessageLite;

import net.jueb.protoServer.controller.ProtoMessageController;
import net.jueb.protoServer.controller.ServiceController;
import net.jueb.protoServer.message.ProtoMessage;
import net.jueb.protoServer.message.ProtoMessage.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

/**
 * 端口消息分发器-处理protoMessage消息的分发器
 * 该分发器对分发到控制器的消息进行了2次解码处理
 * @author Administrator
 */
public final class ProtoMessageDispatcherHandler extends MessageDispatcherHandler<ProtoMessage.Message>{

	protected static final InternalLogger log = InternalLoggerFactory.getInstance(ProtoMessageDispatcherHandler.class);
	
	/**
	 * 针对ProtoMessage.Message消息类型的分发器
	 * @param port 分发器端口
	 * @param dispatcherName 分发器名称
	 * @param controllers 消息映射的目标控制器集合
	 * @param mapping 消息映射规则
	 */
	public ProtoMessageDispatcherHandler(ConcurrentHashMap<Integer, ServiceController<?>> controllers) {
		super(controllers);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void executeController(ChannelHandlerContext ctx, Message msg,@SuppressWarnings("rawtypes") ServiceController controller) throws Exception {
		if(controller!=null && controller instanceof ProtoMessageController<?>)
		{//如果控制器不为空,且消息ID匹配则调用该控制器处理消息
			@SuppressWarnings("rawtypes")
			ProtoMessageController c=(ProtoMessageController)controller;
			MessageLite emsg=msg.getExtension(c.getGeneratedExtension());
			if(emsg!=null)
			{
				log.debug("转换为扩展类型成功");
				c.execute(ctx, emsg);
				return ;
			}
		}
		//只要控制器不匹配或者类型不匹配，就发至默认处理控制器
		log.error("转换为扩展类型失败,转发至默认处理控制器");
		super.executeDefaultController(ctx, msg, controller);
	}
	
}
